package com.inventive.jmscache.server;

import javax.jms.Destination;
import javax.jms.JMSException;
import java.util.List;
import java.util.UUID;

/**
 * @author Grant Little <grant.little@coreservices.com.au>
 */
public abstract class JmsCacheDestination implements Destination {


    protected String name;
    protected DestinationType destinationType;
    protected JmsCacheServer jmsCacheServer;

    protected JmsCacheDestination(JmsCacheServer jmsCacheServer, String name, DestinationType destinationType) {
        this.jmsCacheServer = jmsCacheServer;
        this.name = name;
        this.destinationType = destinationType;
    }

    public void addMessage(JmsCacheMessage message) throws JMSException {
        switch (destinationType) {
            case QUEUE: {
                BackendQueue queue = jmsCacheServer.getQueue(name);
                queue.put(message);
                break;
            }
            default: {
                BackendTopic topic = jmsCacheServer.getTopic(name);
                List<String> subscriptionIds = jmsCacheServer.getSubscriptionsForTopic(name);
                String messageId = UUID.randomUUID().toString();
                if (null == message.getJMSMessageID()) {
                    messageId = message.getJMSMessageID();
                }
                topic.publish(messageId, message);
                for (String subscriptionId : subscriptionIds) {
                    jmsCacheServer.addMessageIdToSubscription(subscriptionId, messageId);
                }
            }
        }
    }

    public JmsCacheMessage receive() throws JMSException {
        BackendQueue queue = jmsCacheServer.getQueue(name);
        return queue.poll();
    }

    public JmsCacheMessage receive(String subscriptionId) throws JMSException {
        BackendTopic topic = jmsCacheServer.getTopic(name);
        return null;
    }

    public JmsCacheMessage receive(long millis) throws JMSException {
        switch (destinationType) {
            case QUEUE: {
                BackendQueue queue = jmsCacheServer.getQueue(name);
                return queue.poll(millis);
            }
            default : {
//                BackendTopic topic = jmsCacheServer.getTopic(name);
//                return topic.poll(millis);
                return null;
            }
        }
    }

    public JmsCacheMessage receive(String subscriptionId, long millis) throws JMSException {
        BackendTopic topic = jmsCacheServer.getTopic(name);
        return null;
    }
}
